package com.zkml.domainmanage.support;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zkml.domainmanage.support.exception.DomainServiceException;
import com.zkml.domainmanage.support.input.PropertiesInput;
import com.zkml.domainmanage.support.vo.PropertyVO;
import com.zkml.domainmanage.support.vo.ResultUtil;
import com.zkml.domainmanage.support.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/domainManage/system")
public class SystemController {

    @Autowired
    SystemService systemService;


    @GetMapping("importList")
    public String importList(String query,Model model){
        List<PropertyVO> propertyList = systemService.importList(query);
        model.addAttribute("importList",propertyList);
        return "importList";
    }

    @PostMapping("doAddImport")
    @ResponseBody
    public ResultVO doAddImport(@Valid PropertiesInput propertiesInput,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultUtil.failResult(bindingResult.getFieldError().getDefaultMessage());
        }
        systemService.doAddImport(propertiesInput.getName(),propertiesInput.getValue());
        return ResultUtil.successResult("");
    }

    @PostMapping("doDeleteImport")
    @ResponseBody
    public ResultVO doDeleteImport(@RequestParam(required = true) String name){
        systemService.doDeleteImport(name);
        return ResultUtil.successResult("删除成功");
    }

    @GetMapping("exampleList")
    public String exampleList(String query,Model model){
        List<PropertyVO> propertyList = systemService.exampleList(query);
        model.addAttribute("exampleList",propertyList);
        return "exampleList";
    }

    @PostMapping("doAddExample")
    @ResponseBody
    public ResultVO doAddExample(@Valid PropertiesInput propertiesInput,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            //如果参数不正确，忽略请求
            return ResultUtil.successResult("");
        }
        systemService.doAddExample(propertiesInput.getName(),propertiesInput.getValue(),propertiesInput.getComment());
        return ResultUtil.successResult("");
    }

    @PostMapping("doDeleteExample")
    @ResponseBody
    public ResultVO doDeleteExample(@RequestParam(required = true) String name){
        systemService.doDeleteExample(name);
        return ResultUtil.successResult("");
    }

    @PostMapping("doImportExample")
    public String doImportExample(MultipartHttpServletRequest request){
        MultipartFile file = request.getFile("file");
        //如果是properties文件，则导入
        if(file.getOriginalFilename().endsWith("properties")){
            systemService.doImportExample(file);
        }
        return "redirect:/domainManage/system/exampleList";
    }

    @PostMapping("doImportExampleForJson")
    public String doImportExampleForJson(String json, HttpServletRequest request){
        //json导入
        try{
            JSONObject jsonObject = JSON.parseObject(json);
            systemService.doImportExampleForJson(jsonObject);
        }catch (Exception e){
            request.setAttribute("error", "json 导入错误， " + e.getMessage());
        }
        return "redirect:/domainManage/system/exampleList";
    }

    @PostMapping("doImportExampleForExcel")
    public String doImportExampleForExcel(@RequestParam MultipartFile file, HttpServletRequest request){
        //excel导入
        try {

            Map<String, String> exampleExcelHead = new HashMap<>();
            exampleExcelHead.put("name", "name"); //字段名称
            exampleExcelHead.put("value", "value");//字段值
            exampleExcelHead.put("example", "example");//示例值
            exampleExcelHead.put("comment", "comment");//字段注释

            if (file.getOriginalFilename().endsWith("xls") || file.getOriginalFilename().endsWith("xlsx")) {
                systemService.doImportExampleForExcel(file.getInputStream(), file.getOriginalFilename(), exampleExcelHead);
            }

        }catch (Exception e){
            request.setAttribute("error", "json 导入错误， " + e.getMessage());
        }
        return "redirect:/domainManage/system/exampleList";
    }

    @GetMapping("example/excel/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response){
        //========================导出=======================
        try {
            org.apache.commons.fileupload.FileItem fileItem = null;
            Resource resource = new ClassPathResource("/download/"+fileName);
            File file = resource.getFile();

            if(! file.exists()){
                return;
            }

            InputStream inStream = new FileInputStream(file);; //读取项目本地“teacherTemplate.xlsx”
            response.reset();
            response.setContentType("application/vnd.ms-excel");// 不同类型的文件对应不同的MIME类型
            response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + fileName);
            byte[] b = new byte[1024];
            int len;
            ServletOutputStream sos = response.getOutputStream();
            while ((len = inStream.read(b)) > 0) {
                sos.write(b, 0, len);
            }
            sos.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("doLoadExampleNames")
    @ResponseBody
    public ResultVO doLoadExampleNames(){
        try{
            systemService.doLoadExampleNames();
            return ResultUtil.successResult("操作成功");
        }catch (DomainServiceException e){
            return ResultUtil.failResult(e.getMessage());
        }
    }
}
